<template>
  <div>
    <h1>{{ id ? "编辑" : "新建" }}视频</h1>
    <el-form label-width="80px" @submit.native.prevent>
      <el-form-item label="所属分类">
        <el-select v-model="model.parent" placeholder="请选择" filterable>
          <el-option
            v-for="item in parents"
            :key="item._id"
            :label="item.name"
            :value="item._id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="视频名称">
        <el-input
          v-model="model.videoname"
          placeholder="请输入视频名称"
        ></el-input>
      </el-form-item>
      <el-form-item label="上传视频">
        <el-upload
          class="avatar-uploader"
          :action="$http.defaults.baseURL + '/upload'"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
        >
          <video v-if="model.video" :src="model.video" class="avatar">
            你的浏览器不支持视频
          </video>
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="save()">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  data() {
    return {
      model: {
        videoname: "",
        parent: "",
        video: ""
      },
      parents: []
    };
  },
  props: {
    id: { type: String }
  },

  methods: {
    fetchparents() {
      this.$http.get("/rest/categories").then(res => {
        this.parents = res.data;
      });
    },
    handleAvatarSuccess(res) {
      this.$set(this.model, "video", res.url);
    },

    save() {
      if (this.id) {
        this.$http.put(`/rest/videos/${this.id}`, this.model).then(() => {
          this.$message({
            message: "修改成功",
            type: "success"
          });
        });
        this.$router.push("/shipin/list");
      } else {
        this.$http.post("/rest/videos", this.model).then(() => {
          // console.log(res.data);
          this.$message({
            message: "保存成功",
            type: "success"
          });
        });
        this.$router.push("/shipin/list");
      }
    },

    fetch() {
      this.$http.get(`/rest/videos/${this.id}`).then(res => {
        this.model = res.data;
      });
    }
  },

  created() {
    this.id && this.fetch();
    this.fetchparents();
  }
};
</script>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
